package com.cdy.demo.algorithm;

import java.util.Stack;

public class Leetcode2 {

	public static void main(String[] args) {
		Leetcode2 Leetcode5 = new Leetcode2();

		ListNode listNode = new ListNode(3, null);
		ListNode listNode1 = new ListNode(4, listNode);
		ListNode listNode2 = new ListNode(2, listNode1);

		ListNode listNode3 = new ListNode(4, null);
		ListNode listNode4 = new ListNode(6, listNode3);
		ListNode listNode5 = new ListNode(5, listNode4);
		Leetcode5.addTwoNumbers(listNode2, listNode5);


	}

	public static class ListNode {
		int val;
		ListNode next;
		ListNode() {}
		ListNode(int val) { this.val = val; }
		ListNode(int val, ListNode next) { this.val = val; this.next = next; }
	}

	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

		ListNode temp = l1;
		int len1 = 1;
		while (temp.next != null) {
			temp = temp.next;
			len1++;
		}
		temp = l2;
		int len2 = 1;
		while (temp.next != null) {
			temp = temp.next;
			len2++;
		}

		int val = l1.val + l2.val;
		int j = 0;
		ListNode listNode = new ListNode();
		if (val >= 10) {
			listNode.val = val - 10;
			j = 1;
		} else{
			listNode.val = val;
		}
		temp = listNode;
		int len = Math.max(len1, len2);
		while (--len > 0) {
			int pop1 = l1 == null ? 0 : (l1.next == null ? 0 : l1.next.val);
			int pop2 = l2 == null ? 0 : (l2.next == null ? 0 : l2.next.val);
			int sum = pop1 + pop2 + j;
			j = 0;
			if (sum >= 10) {
				j = 1;
			}
			ListNode next = new ListNode();
			if (sum >= 10) {
				next.val = sum-10;
				j = 1;
			} else{
				next.val = sum;
			}
			temp.next = next;
			temp = next;
			l1 = l1 == null ? null : (l1.next == null ? null : l1.next);
			l2 = l2 == null ? null : (l2.next == null ? null : l2.next);
		}
		if (j == 1) {
			ListNode next = new ListNode();
			next.val = 1;
			temp.next = next;
		}
		return listNode;
	}

}
